<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      :style="`height: ${height}; overflow-y: hidden;`"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
      @onDestroyed="handleDestroyed"
    />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'

import { onBeforeUnmount, ref, shallowRef, watch, nextTick } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: '请输入内容...'
  },
  height: {
    type: String,
    default: '500px'
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const editorRef = shallowRef()
const valueHtml = ref('')
const mode = 'default'

const toolbarConfig = {}

const editorConfig = {
  placeholder: props.placeholder,
  readOnly: props.disabled,
  MENU_CONF: {
    fontColor: {
      colors: ['#000000', '#333333', '#666666', '#999999', '#cccccc', '#ffffff', '#61affe', '#16baaa', '#07c160', '#fa5151', '#ff9500']
    },
    bgColor: {
      colors: ['#000000', '#333333', '#666666', '#999999', '#cccccc', '#ffffff', '#61affe', '#16baaa', '#07c160', '#fa5151', '#ff9500']
    }
  }
}

onBeforeUnmount(() => {
  if (editor) {
    editor.destroy()
    editor = null
  }
})

// 编辑器创建完成时的回调函数
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
  
  // 确保编辑器完全初始化后再设置内容
  setTimeout(() => {
    const initialValue = props.modelValue || ''
    if (initialValue) {
      try {
        // 确保编辑器处于可用状态
        if (!editor.isDestroyed && editor.setHtml) {
          // 先清空编辑器，确保没有残留状态
          editor.clear()
          // 设置HTML内容
          editor.setHtml(String(initialValue))
        }
      } catch (error) {
        console.warn('设置HTML内容失败，尝试纯文本模式:', error)
        try {
          if (!editor.isDestroyed) {
            editor.clear()
            const textContent = String(initialValue).replace(/<[^>]*>/g, '')
            if (textContent.trim()) {
              editor.insertText(textContent)
            }
          }
        } catch (textError) {
          console.error('设置文本内容也失败:', textError)
        }
      }
    }
  }, 200) // 增加延迟确保编辑器完全准备好
}

const handleChange = (editor) => {
  // 防止循环更新
  const currentHtml = editor.getHtml()
  if (currentHtml !== valueHtml.value) {
    valueHtml.value = currentHtml
    emit('update:modelValue', currentHtml)
    emit('change', currentHtml)
  }
}

const handleDestroyed = (editor) => {
  // 编辑器销毁处理
}

watch(() => props.modelValue, (newValue) => {
  const editor = editorRef.value
  if (!editor) return
  
  const newValueStr = String(newValue || '')
  const currentHtml = editor.getHtml()
  
  // 只在内容真正不同时才更新
  if (newValueStr !== currentHtml && newValueStr !== valueHtml.value) {
    valueHtml.value = newValueStr
    
    // 延迟更新，避免与编辑器内部状态冲突
    setTimeout(() => {
      try {
        // 检查编辑器是否仍然存在且可用
        if (editor.isDestroyed || !editor.setHtml) {
          return
        }
        
        // 直接使用setHtml，因为后台返回的是标准HTML
        editor.setHtml(newValueStr)
      } catch (error) {
        console.warn('更新HTML内容失败，尝试纯文本模式:', error)
        try {
          if (!editor.isDestroyed) {
            editor.clear()
            const textContent = newValueStr.replace(/<[^>]*>/g, '')
            if (textContent.trim()) {
              editor.insertText(textContent)
            }
          }
        } catch (textError) {
          console.error('更新文本内容也失败:', textError)
        }
      }
    }, 50)
  }
}, { immediate: true })

watch(() => props.disabled, (newDisabled) => {
  const editor = editorRef.value
  if (editor == null) return
  
  if (newDisabled) {
    editor.disable()
  } else {
    editor.enable()
  }
})

</script>

<style scoped>
.rich-text-editor {
  min-height: 500px;
}

/* 确保编辑器有足够的空间 */
:deep(.w-e-text-container) {
  min-height: 450px !important;
}

:deep(.w-e-toolbar) {
  border-bottom: 1px solid #ccc;
}

:deep(.w-e-text-placeholder) {
  color: #999;
  font-style: italic;
}
</style>
